/*
 项目授权
 对应模板mysoft_back\tenant\authorize.html
 */
import util from '@yunke/core/util';
import angular from 'angular';
import $ from 'jquery';
import ui from '@yunke/core/ui';
import _ from 'lodash';
import '../../../../tenant/dialog/remind.css';
// import '../../../../tenant/dialog/css/authorize_batch.less'
import authorize from 'authorize';
import '@yunke/angular-ui/lib/uiCheckboxArray';
import receivableInfoUrl from '../../../../tenant/dialog/receivable_info.html';
import setRemindTemplate from '../../../../tenant/dialog/set_remind.html';
import getRemindTemplate from '../../../../tenant/dialog/get_remind.html';
import informationTemplate from '../../../../tenant/dialog/information.html';
import authorizeBatchTemplate from '../../../../tenant/dialog/authorize_batch.html';
import projInfoTemplate from '../../../../tenant/dialog/proj_info.html';
import showDeliveryInfoTemplate from '../../../../tenant/dialog/show-delivery-info.html';

require('@yunke/core/angular_public_interceptor');
import permision from '../../permission'

let app = angular.module('ctrlTenantAuthorize',
    ['angularPublicInterceptor', 'ngPublicUI', 'angular.directive.uiCheckboxArray']);

const xq = [
    {
        text: '全部',
        value: ''
    }, {
        text: '续签',
        value: '1'
    }, {
        text: '不续签',
        value: '0'
    }, {
        text: '未确认',
        value: null
    }
];

const xqConstant = {
    '1': '商务谈判中',
    '2': '合同流程中',
    '3': '款项申请中',
    '4': '续签完成'
};

const notXqConstant = {
    '1': '项目售罄',
    '2': '应用不好',
    '3': '其他'
};

const htStatus = [
    {
        name: '全部',
        field: ''
    }, {
        name: '正常',
        field: 'normal'
    }, {
        name: '即将过期',
        field: 'will_expire'
    }, {
        name: '已过期',
        field: 'expire'
    }, {
        name: '已禁用',
        field: 'overdue'
    }
];

app.filter('xqResult', function () {
    return function (origin, result) {

        if (origin == null) {
            return _.find(xq, x => x.value === origin).text;
        }

        const isXq = _.find(xq, x => x.value === origin).text;

        result = origin == 1 ? xqConstant[result] : origin == 0 ? notXqConstant[result] : '';

        if (!!result) {
            result = `(${result})`;
        }

        return isXq + result;
    };
}).controller('tenantAuthorizeCtl', [
    '$rootScope', '$scope', '$http', '$timeout', '$q', ($rootScope, $scope, $http, $timeout, $q) => {

        $scope.receivableInfoUrl = receivableInfoUrl;
        $scope.setRemindTemplate = setRemindTemplate;
        $scope.getRemindTemplate = getRemindTemplate;
        $scope.informationTemplate = informationTemplate;
        $scope.authorizeBatchTemplate = authorizeBatchTemplate;
        $scope.projInfoTemplate = projInfoTemplate;
        $scope.showDeliveryInfoTemplate = showDeliveryInfoTemplate;

        const getGuid = array => _.filter(_.uniq(_.map(array, x => x['user_guid'])), x => !!x);

        $scope.tabTypes = {
            title: '',
            field: 'tabType',
            defaultValue: 'project',
            selectItems: [
                {
                    name: '项目维度',
                    field: 'project'
                }, {
                    name: '产品维度',
                    field: 'product'
                }
            ]
        };

        $scope.tabType = $scope.tabTypes.defaultValue;

        $scope.htStatusList = _.map(_.filter(_.cloneDeep(htStatus), x => x.field), x => {
            x['text'] = x['name'];
            x['value'] = x['field'];
            x['checked'] = _.some(['normal', 'will_expire', 'expire'], y => y === x['field']);
            if (x['checked']) {
                $scope.orgStateList = $scope.orgStateList || [];
                $scope.orgStateList.push(x);
            }
            return x;
        });

        $scope.jfry = [];

        $scope.areaIdConst = {
            title: '区域：',
            field: 'areaId',
            defaultValue: '',
            selectItems: [
                {
                    name: '全部',
                    field: ''
                }
            ]
        };

        $scope.disableConst = {
            title: '租户状态：',
            field: 'disable',
            defaultValue: '1',
            selectItems: [
                {
                    name: '全部',
                    field: ''
                }, {
                    name: '启用',
                    field: '1'
                }, {
                    name: '禁用',
                    field: '0'
                }
            ]
        };

        $scope.orgStateConst = {
            title: '租期状态：',
            field: 'orgState',
            defaultValue: '',
            selectItems: htStatus
        };

        $scope.isXqConst = {
            title: '汇报状态：',
            field: 'isXq',
            defaultValue: '',
            selectItems: [
                {
                    name: '全部',
                    field: ''
                }, {
                    name: '续签',
                    field: '1'
                }, {
                    name: '不续签',
                    field: '0'
                }, {
                    name: '未确定',
                    field: 'null'
                }
            ]
        };

        ajax({
            url: '/api/index.php?r=/contract/get-contract-area-list',
            success: (res) => {
                $scope.$apply(() => {
                    res.data.forEach(v => {
                        $scope.areaIdConst.selectItems.push({
                            name: v.areaName,
                            field: v.areaId
                        });
                    });
                });
            }
        });

        //分页数据渲染
        $scope.pageIndex = 1;
        $scope.pageSize = 5;
        $scope.pageTotal = '';
        $scope.authListPageChange = ($pageIndex, $pageSize) => {
            $scope.pageIndex = $pageIndex;
            $scope.pageSize = $pageSize;
            getAuthData($http, $scope);
        };
        //搜索数据渲染
        $scope.search = (pageIndex) => {
            if (pageIndex !== undefined) {
                $scope.pageIndex = pageIndex;
            }
            getAuthData($http, $scope);
        };

        //导出excel表
        $scope.downloadExcel = () => {
            getAuthData($http, $scope, true);
        };

        //同步
        $scope.syncAuthProject = () => {
            getSyncAuthProject($http, $scope);
        };

        // 展示租户详情
        $scope.showInfomation = ($dialog, $dialogScope, tenant) => {
            $dialogScope.basicInfo = tenant;
        };

        // 展示项目详情
        $scope.showProjInfo = ($dialog, $dialogScope, tenant) => {
            $dialogScope.projInfo = tenant;
        };

        // 查看交付信息
        $scope.showAuthorizeArea = ($dialog, $dialogScope, tenant, project, index, updateAuthInfo) => {
            $dialogScope.profile = {};
            $dialogScope.updateAuthInfo = updateAuthInfo;

            $http.get('/orgapi/index.php?r=project/get-contact', {
                params: {
                    orgId: tenant.Id,
                    projectId: project.ProjId
                }
            }).then(res => {
                $dialogScope.profile = res.data.data;
            });

            // 编辑交付信息
            $dialogScope.editAuthorizeArea = ($innerDialog, $innerDialogScope, profile) => {

                profile = JSON.parse(JSON.stringify(profile));

                $innerDialogScope.profile = profile;

                $innerDialogScope.localAdd = function (key) {

                    const id = _.uniqueId();

                    $innerDialogScope.profile[key] = $innerDialogScope.profile[key] || [];

                    $innerDialogScope.profile[key].push({id, name: '', mobile: '', email: ''});

                    autoCompleteInit(id);

                };

                $innerDialogScope.localUpdate = function (key, item) {

                    if (!item.id) {
                        item.id = _.uniqueId();
                    }
                    autoCompleteInit(item.id);

                };

                $innerDialogScope.localRemove = function (key, item) {

                    $innerDialogScope.profile[key] = _.filter($innerDialogScope.profile[key], x => x.id != item.id);

                };

                // 初始化
                _.each(profile, (value, key) => {
                    if (!value.length) {
                        $innerDialogScope.localAdd(key);
                    } else {
                        _.each(value, x => $innerDialogScope.localUpdate(key, x));
                    }
                });

                $http.get('/orgapi/index.php?r=project/get-contact-change-log', {
                    params: {
                        orgId: tenant.Id,
                        projectId: project.ProjId
                    }
                }).then(res => {
                    $innerDialogScope.historyList = res.data.data;
                });

                function autoCompleteInit(id) {
                    $timeout(() => {
                        $('#edit-delivery-info-username' + id).autoComplete({
                            url: '/api/index.php?r=erp-interface/get-users',
                            id,
                            select: function (vals) {
                                $innerDialogScope.$apply(() => {
                                    let item = _.find($innerDialogScope.profile[vals.type], x => x.id == vals.id);
                                    item.name = vals.name;
                                    item.mobile = vals.phone.replace(/^(\+86)/g, '');
                                    item.email = vals.email;
                                    item.user_guid = vals.guid;
                                });
                            }
                        });
                    });
                }
            };

            // 保存交付信息
            $dialogScope.saveAuthorizeArea = ($innerDialog, $innerDialogScope) => {
                'CustomManager CustomManagerPhone CustomManagerEmail Deliver DeliverPhone DeliverEmail'.split(' ')
                    .forEach(v => {
                        $scope.$apply(
                            () => {
                                $scope.authData[index][v] = $innerDialogScope.profile[v];
                            });
                    });

                $http.post('/api/index.php?r=project/update-contact', {
                    orgId: tenant.Id,
                    projectId: [project.ProjId],
                    custom_manage_guid: getGuid($innerDialogScope.profile['custom_manage']),
                    deliver_guid: getGuid($innerDialogScope.profile['deliver']),
                    USE_FORM_DATA: false,
                    is_batch: false
                }).then(res => {
                    getAuthData($http, $scope);
                    $dialog.close();
                    util.notify('保存成功', 1000);
                });
            };
        };

        //查看绑定项目明细
        $scope.showBindProjectInfo = (data, $dialog, $dialogScope) => {
            $dialogScope.projectInfoList = $dialogScope.data.data;
            setTimeout(() => {
                $dialog.reset();
                $('.project-bind-info tr').each(function (index) {
                    $(this).find('td:first').html(index++);
                });
            }, 0);
        };

        const needRenewContractsCatch = {};

        needRenewContractsCatch.get = (orgname) => {
            if (needRenewContractsCatch[orgname]) {
                return $q.resolve(needRenewContractsCatch[orgname]);
            } else {
                return $http.get('/orgapi/index.php?r=mtp/myscrm-organization/get-need-renew-contract-list', {
                    params: {orgname}
                }).then(res => {
                    needRenewContractsCatch[orgname] = res.data.data;
                    return needRenewContractsCatch[orgname];
                });
            }
        };

        let pDialog;

        /**
         * 续签确认设置
         * @param tenant
         * @param contract
         * @param $dialog
         * @param $dialogScope
         * @param projectId
         */
        $scope.showSetRemind = (tenant, contract = {}, $dialog, $dialogScope, projectId) => {

            pDialog = $dialog;
            const organizationId = tenant.Id;
            const orgname = tenant.UniqueName;

            let $data = $dialogScope.data;

            $dialogScope.isProject = !!projectId;
            $dialogScope.organizationId = organizationId;
            $dialogScope.close = () => $dialog.close();
            $data.renewStatus = '1';
            $data.noRenewReason = '1';

            $dialogScope.cites = [
                {
                    text: '全部',
                    value: ''
                }];

            $dialogScope.city = '';

            $dialogScope.htStatus = _.filter(htStatus, x => x.field !== 'normal' && x.field !== 'overdue');

            $dialogScope.status = '全部';

            $dialogScope.xqStatus = xq;

            $dialogScope.xq = '';

            $dialogScope.maxStep = 2;

            $dialogScope.step = 1;

            $dialogScope.allChecked = false;

            $dialogScope.allCheckedClick = () => {

                _.each($dialogScope.items, item => {
                    if (item.IsXq == null) {
                        item.checked = $dialogScope.allChecked;
                    }
                });

            };

            $dialogScope.prev = () => {

                if ($dialogScope.step > 1) {
                    $dialogScope.step--;
                }

            };

            $dialogScope.next = () => {

                if (projectIdAndAppCode().length && $dialogScope.step < $dialogScope.maxStep) {
                    $dialogScope.step++;
                    getRemindDetails();
                } else {
                    ui.showSucTip('请选择应用');
                }

            };

            //$dialogScope.projCheckedDisabled = false; // 不续签时, 续签明细全反选且不可选

            const select = (value) => projects => _.each(projects,
                project => _.each(project.apps, app => app.isXq = value));

            const projectIdAndAppCode = () => _.map(_.filter($dialogScope.items, 'checked'), x => {
                return {
                    projectId: x.ProjectId,
                    appCode: x.AppCode
                };
            });

            const ukName = () => projectId ? 'projectId' : 'contractId';
            const ukId = () => projectId ? projectId : $dialogScope.contractId;

            const getRemindDetails = () =>
                $http.post(
                    `/orgapi/index.php?r=mtp/myscrm-organization/get-remind-details&${ ukName() }=${ ukId() }&organizationId=${ organizationId }`,
                    {
                        projectIdAndAppCode: projectIdAndAppCode(),
                        USE_FORM_DATA: true
                    }).then(res => {

                    const projects = res.data.data || [];

                    // 默认不选择
                    //select('0')(projects);

                    _.merge($data, contract, {
                        organizationId,
                        contractId: $dialogScope.contractId,
                        isXq: '1',
                        projects
                    });

                });

            const getRemindDetailStepOne = () => $http.get(
                '/orgapi/index.php?r=mtp/myscrm-organization/get-remind-details-step-one', {
                    params: {
                        [ukName()]: ukId(),
                        organizationId,
                        orgName: orgname
                    }
                }).then(res => {

                const data = res.data.data;

                $dialogScope.rawItems = _.cloneDeep(data);

                $dialogScope.items = data;
                $dialogScope.cites = _.concat($dialogScope.cites,
                    _.map($dialogScope.items, item => ({
                        text: item.City,
                        value: item.City
                    })));
                $dialogScope.cites = _.uniqBy($dialogScope.cites, 'value');

            });

            needRenewContractsCatch.get(orgname).then(data => $dialogScope.needRenewContracts = data).then(() => {

                $dialogScope.contractId = contract.ContractId;

                // 默认未确认
                getRemindDetailStepOne().then(() => $dialogScope.xq = null);

            });

            const watchFn = (value, field) => {

                $dialogScope.items = _.filter($dialogScope.items, x => {

                    if (value === '' || value === '全部') {
                        return true;
                    } else {
                        if (x[field] == value) {
                            return true;
                        } else {
                            x.checked = false;
                            return false;
                        }
                    }

                });

            };

            $dialogScope.$watchGroup(['city', 'status', 'xq'], (newValues, oldValues) => {

                $dialogScope.localSearch();

            });

            $dialogScope.localSearch = () => {

                $dialogScope.items = _.filter($dialogScope.rawItems,
                    item => new RegExp($dialogScope.projectName).test(item['ProjectName']));
                watchFn($dialogScope.city, 'City');
                watchFn($dialogScope.status, 'Status');
                watchFn($dialogScope.xq, 'IsXq');

            };

            //是否禁用项目选择
            $dialogScope.$watch('data.isXq', (newValue) => {

                if (+newValue === 0) {
                    select('0')($data.projects);
                } else if (+newValue === 1 || +newValue === 2) {
                    select('1')($data.projects);
                } else {
                    //
                }

            });

            $dialogScope.toggleActive = (app, isXq) => {

                // 全部续签 不续签不能点
                if (+$dialogScope.data.isXq === 0 || +$dialogScope.data.isXq === 2) {
                    return;
                }

                if (+isXq === 2) {
                    app.isXq = '1';
                } else {
                    app.isXq = +app.isXq === 1 ? '0' : '1';
                }

            };

        };

        $scope.remindTpl = `<div style="text-align: center;">
                                <a class="tab-text"
                                   style="display: block;"
                                   ui-dialog="续签汇报"
                                   ui-dialog-init="showSetRemind(tenant, contract, $dialog, $dialogScope)"
                                   ui-dialog-template="{{setRemindTemplate}}">
                                    合同维度
                                </a>
                                <a class="tab-text"
                                   style="display: block;"
                                   ui-dialog="续签汇报"
                                   ui-dialog-init="showSetRemind(tenant, contract, $dialog, $dialogScope, project.ProjId)"
                                   ui-dialog-template="{{setRemindTemplate}}">
                                    项目维度
                                </a>
                        </div>`;

        /**
         * 续签设置
         * @param $data
         * @param $dialog
         * @param $dialogScope
         */
        $scope.setRemind = ($data, isProject, items) => {

            const params = {
                organizationId: $data.organizationId,
                contractId: $data.contractId,
                reason: $data.reason,
                isXq: +!!+$data.isXq,
                renewStatus: $data.renewStatus,
                noRenewReason: $data.noRenewReason,
                details: _.map($data.projects, project => {
                    project = _.pick(project, 'projectId', 'apps');
                    project.apps = _.map(project.apps, app => {
                            const item = _.find(items,
                                item => item['ProjectId'] === project['projectId'] && item['AppCode'] === app['appCode']);
                            let contractId;
                            if (item) {
                                contractId = item['ContractId'];
                            }
                            return _.pick(
                                _.merge({
                                    isXq: '0',
                                    contractId
                                }, app), 'appCode', 'isXq', 'contractId');
                        }
                    );
                    return project;
                })
            };

            if (isProject) {
                delete params.contractId;
            }

            $http.post('/orgapi/index.php?r=mtp/myscrm-organization/add-remind', params).then((res) => {
                if (res.data.data) {
                    ui.showSucTip('续签设置成功');
                    if (pDialog && pDialog.close) {
                        pDialog.close();
                    }
                    getAuthData($http, $scope);
                } else {
                    ui.showSucTip('续签设置失败');
                }
            });
        };

        /**
         * 查看续签设置
         * @param tenant
         * @param $dialog
         * @param $dialogScope
         */
        $scope.showGetRemind = (tenant, contract, project, $dialog, $dialogScope) => {

            // TODO get remind 重新汇报的时候 直接调用设置的第二个步骤。

            const setEditable = () => {
                $dialogScope.showGetRemindOkValue = '确定';
                $dialogScope.editing = true;
                if (!dsdGet('renewStatus')) {
                    dsdSet('renewStatus', '1');
                }
                if (!dsdGet('noRenewReason')) {
                    dsdSet('noRenewReason', '1');
                }
            };

            const setViewer = () => {
                $dialogScope.showGetRemindOkValue = '重新汇报';
                $dialogScope.editing = false;
            };

            const isEditing = () => $dialogScope.editing;

            const isNotEditing = _.negate(isEditing);

            const close = () => $dialog.close();

            const select = (value) => projects => _.each(projects,
                project => _.each(project.apps, app => app.isXq = value));

            const canNotUpdate = () => _.filter(dsdGet('projects'),
                project => _.every(project.apps, app => !app['isCanUpdate'])).length;

            /**
             * dialogScope.data -> prop -> dsdGet
             * @param prop
             */
            const dsdGet = (prop) => _.get($dialogScope.data, prop);

            const dsdSet = (prop, value) => _.set($dialogScope.data, prop, value);

            const updateRemind = ($dialog, $dialogScope, $data) => {

                const params = {
                    organizationId: tenant.Id,
                    remindId: $data.remindId,
                    reason: $data.reason,
                    isXq: +!!+$data.isXq,
                    renewStatus: $data.renewStatus,
                    noRenewReason: $data.noRenewReason,
                    details: _.map($data.projects, project => {
                        project = _.pick(project, 'projectId', 'apps');
                        project.apps = _.filter(_.map(project.apps, app => {
                                return _.pick(
                                    _.merge({
                                        isXq: '0'
                                    }, app), 'appCode', 'isXq', 'contractId', 'isCanUpdate');
                            }
                        ), 'isCanUpdate');
                        return project;
                    })
                };

                $http.post('/orgapi/index.php?r=mtp/myscrm-organization/update-remind', params).then((res) => {
                    if (res.data.data) {
                        ui.showSucTip('重新汇报成功');
                        close();
                        getAuthData($http, $scope);
                    } else {
                        ui.showSucTip('重新汇报失败');
                    }
                });
            };

            const click = ($dialog, $dialogScope, $data) => {
                if (isEditing() && !canNotUpdate()) {
                    //  重新汇报
                    updateRemind($dialog, $dialogScope, $data);
                } else {
                    setEditable();
                }
            };

            const addMethodToScope = (methods = {}, scope = $dialogScope) => _.extend(scope, methods);

            addMethodToScope({isEditing, isNotEditing, close, click, canNotUpdate});

            //是否禁用项目选择
            $dialogScope.$watch('data.isXq', (newValue, oldValue) => {

                if (newValue == '0') {
                    select('0')(dsdGet('projects'));
                } else if (newValue == '1' || newValue == '2') {
                    select('1')(dsdGet('projects'));
                } else {
                    //
                }

            });

            $dialogScope.toggleActive = (app, isXq) => {

                // 全部续签 不续签不能点
                // !isCanUpdate 更新续签时，项目应用已禁用的过滤、项目应用有新的授权的过滤
                if (dsdGet('isXq') == '0' || dsdGet('isXq') == '2') {
                    return;
                }

                if (isXq == '2') {
                    app.isXq = '1';
                } else {
                    app.isXq = app.isXq == '1' ? '0' : '1';
                }

            };

            setViewer();

            $http.get('/orgapi/index.php?r=mtp/myscrm-organization/get-remind', {
                params: {
                    organizationId: tenant.Id,
                    projectId: project.ProjId,
                    appCode: contract.appCode
                }
            }).then((res) => {

                const data = res.data.data || {};

                const isXq = !!data.renewStatus && !!data.noRenewReason ? '1' : !!data.renewStatus ? '2' : '0';

                _.merge($dialogScope.data, data, {isXq, projects: data.details});

            });
        };

        /**
         *
         */
        $scope.getReceivableInfoUrl = ($dialogScope, contract) => {
            $http.get('/api/index.php?r=/receivable/get-receivable&contractManageId=' + contract['ContractManageId'])
                .then(res => {
                    $dialogScope.info = res.data.data;
                    $dialogScope.info.ContractNum = contract.ContractNum;
                });
        };

        $scope.showAuthorizeBatch = ($dialog, $dialogScope, tenant) => {

            let maxStep = 1;

            $dialogScope.projectName = tenant['FriendlyName'];

            $dialogScope.selectedProjects = [];

            $dialogScope.step = 0;

            $dialogScope.nextStep = () => $dialogScope.step < maxStep && ++$dialogScope.step;

            $dialogScope.prevStep = () => $dialogScope.step && --$dialogScope.step;

            $dialogScope.close = () => $dialog.close();

            $dialogScope.authorizeBatchSave = () => {

                $http.post('/api/index.php?r=project/update-contact', {
                    orgId: tenant.Id,
                    projectId: _.map($dialogScope.selectedProjects, x => x['ProjId']),
                    custom_manage_guid: getGuid($dialogScope.profile['custom_manage']),
                    deliver_guid: getGuid($dialogScope.profile['deliver']),
                    USE_FORM_DATA: false,
                    is_batch: true
                }).then(res => {
                    getAuthData($http, $scope);
                    $dialog.close();
                    util.notify('保存成功', 1000);
                });
            };

            $http.get('/orgapi/index.php?r=project/get-project&orgId=' + tenant.Id).then(res => {

                $dialogScope.projects = _.map(res.data.data, x => {
                    x.text = x['ProjName'];
                    x.value = x['ProjId'];
                    return x;
                });

            });

            (function () {

                $dialogScope.profileValid = () => _.every($dialogScope.profile, x => _.some(x, y => y['user_guid']));

                $dialogScope.profile = {
                    custom_manage: [],
                    deliver: []
                };

                $http.get('/orgapi/index.php?r=mtp/myscrm-organization/get-org-deliver&orgId=' + tenant.Id)
                    .then(res => {

                        $dialogScope.profile['custom_manage'][0]['name'] = res.data.data['CustomManager'];
                        $dialogScope.profile['custom_manage'][0]['mobile'] = res.data.data['CustomManagerPhone'];
                        $dialogScope.profile['custom_manage'][0]['email'] = res.data.data['CustomManagerEmail'];
                        $dialogScope.profile['custom_manage'][0]['user_guid'] = res.data.data['CustomManagerGUID'];

                        $dialogScope.profile['deliver'][0]['name'] = res.data.data['Deliver'];
                        $dialogScope.profile['deliver'][0]['mobile'] = res.data.data['DeliverPhone'];
                        $dialogScope.profile['deliver'][0]['email'] = res.data.data['DeliverEmail'];
                        $dialogScope.profile['deliver'][0]['user_guid'] = res.data.data['DeliverGUID'];

                    });

                $dialogScope.localAdd = function (key) {

                    const id = _.uniqueId();

                    $dialogScope.profile[key] = $dialogScope.profile[key] || [];

                    $dialogScope.profile[key].push({id, name: '', mobile: '', email: ''});

                    autoCompleteInit(id);

                };

                $dialogScope.localRemove = function (key, item) {

                    $dialogScope.profile[key] = _.filter($dialogScope.profile[key], x => x.id != item.id);

                };

                // 初始化
                _.keys($dialogScope.profile).map($dialogScope.localAdd);

                function autoCompleteInit(id) {
                    $timeout(() => {
                        $('#edit-delivery-info-username' + id).autoComplete({
                            url: '/api/index.php?r=erp-interface/get-users',
                            id,
                            select: function (vals) {
                                $dialogScope.$apply(() => {
                                    let item = _.find($dialogScope.profile[vals.type], x => x.id == vals.id);
                                    item.name = vals.name;
                                    item.mobile = vals.phone.replace(/^(\+86)/g, '');
                                    item.email = vals.email;
                                    item.user_guid = vals.guid;
                                });
                            }
                        });
                    });
                }

            })();

        };

        $scope.changeCondition = (type, field, notFetchNew) => {
            $timeout(() => {
                $scope[type] = field;
                if (type === $scope.areaIdConst.field) {
                    $scope.getAuthDeliveryList();
                }
                if (!notFetchNew || $scope.appCode) {
                    getAuthData($http, $scope);
                }
            }, 0)
        };

        // ...
        // 初始化默认状态, 从云客参谋跳转过来
        const status = util.getUrlPara('status');
        const isXq = util.getUrlPara('isXq');
        const contactUserId = util.getUrlPara('contactUserId');
        if (status) {
            $scope.orgStateList = [];
            _.some($scope.htStatusList, x => {
                x['checked'] = x['value'] === status;
                if (x['checked']) {
                    $scope.orgStateList.push(x);
                }
                return x['checked'];
            });
        }

        if (isXq) {
            $scope.isXq = isXq;
        }
        if (contactUserId) {
            $scope.contactUserId = contactUserId;
        }
        if (status || isXq || contactUserId) {
            $scope.tabType = $scope.tabTypes.selectItems[1].field;
        }

        $scope.showIsXq = () => _.some(['will_expire', 'expire'], x => _.some($scope.orgStateList, y => y['value'] === x));

        $scope.getAuthData = () => $timeout(() => {
            getAuthData($http, $scope);
        }, 0);


        $scope.getAuthDeliveryList = () => $http.get('/orgapi/index.php?r=mtp/myscrm-organization/get-auth-delivery-list'
            + _.toPairs({
                appCode: $scope.appCode || '',
                areaId: $scope.areaId || $scope.areaIdConst.defaultValue,
                disable: $scope.disable || $scope.disableConst.defaultValue,
                isXq: ($scope.showIsXq() && $scope.isXq) || '',
                orgState: _.map(_.filter($scope.orgStateList, 'checked'), 'value'),
                keyword: $scope.keyword || '',
                type: $scope.tabType
            })
                .map(xs => {
                    if (_.isArray(xs[1])) {
                        return _.map(xs[1], x => `&${xs[0]}[]=${x}`).join('');
                    } else {
                        return `&${xs[0]}=${xs[1]}`;
                    }
                })
                .join('')
        ).then((res) => {
            res.data.data = _.concat([{UserName: '全部', value: ''}], res.data.data, [{UserName: '空', UserGUID: 'Null'}]);
            $scope.contactUsers = _.map(res.data.data, x => {
                return {
                    name: x['UserName'],
                    value: x['UserGUID']
                }
            })
        });

        $scope.getAllApplicationList = () => $http.get('/orgapi/index.php?r=mtp/myscrm-organization/get-all-application-list')
            .then(res => {
                res.data.data = _.concat([{appName: '全部', value: ''}], res.data.data);
                $scope.apps = _.map(res.data.data, x => {
                    return {
                        name: x['appName'],
                        value: x['appCode']
                    }
                })
            });

        authorize.getUserInfoPromise().then((userinfo) => {
            $scope.showContactUser = +userinfo.isAreaCharge === 1;
            $scope.showContactUser = true;
        });

        $scope.getAuthDeliveryList();

        //初始化数据渲染
        $scope.getAllApplicationList()
            .then(() => getAuthData($http, $scope));

    }]);

let isInterruptContinue = true;

function getAuthData($http, $scope, isDownloadExcel) {

    ui.loading(null, isDownloadExcel ? '导出中...' : '正在加载...');
    let url = isDownloadExcel
        ? '/orgapi/index.php?r=mtp/myscrm-organization/export-org-project-auth-list'
        : '/orgapi/index.php?r=mtp/myscrm-organization/get-org-project-auth-list';

    url += `&type=${$scope.tabType}`;

    const params = _.toPairs({
        appCode: $scope.appCode || '',
        contactUserId: $scope.showContactUser ? $scope.contactUserId || '' : '',
        areaId: $scope.areaId || $scope.areaIdConst.defaultValue,
        disable: $scope.disable || $scope.disableConst.defaultValue,
        isXq: ($scope.showIsXq() && $scope.isXq) || '',
        orgState: _.map(_.filter($scope.orgStateList, 'checked'), 'value'),
        keyword: $scope.keyword || '',
        pageIndex: $scope.pageIndex,
        pageSize: $scope.pageSize
    })
        .map(xs => {
            if (_.isArray(xs[1])) {
                return _.map(xs[1], x => `&${xs[0]}[]=${x}`).join('');
            } else {
                return `&${xs[0]}=${xs[1]}`;
            }
        })
        .join('');

    isInterruptContinue = false;

    return $http.get(url + params)
        .then(res => {

            isInterruptContinue = true;

            permision
                .getData((data) => {
                    $scope.userAuthList = data;
                    $scope.hasPermission1013 = $scope.userAuthList.indexOf('1013') !== -1;
                    $scope.hasPermission1014 = $scope.userAuthList.indexOf('1014') !== -1;
                });

            res = res.data;

            if (isDownloadExcel) {
                return location.href = res.data;
            }

            $scope.overview = $scope.overview || {};
            $scope.overview.authCount = res.data.authCount;
            $scope.overview.projectCount = res.data.projectCount;
            $scope.overview.payAuthCount = res.data.payAuthCount;
            $scope.overview.freeAuthCount = res.data.freeAuthCount;
            $scope.overview.total = res.data.orgCount;

            const interrupt = (tenant) => {
                const chunks = _.chunk(tenant['applications'], 10);
                const loop = () => {
                    tenant['applicationsView'] = tenant['applicationsView'] || [];
                    if (chunks.length && isInterruptContinue) {
                        setTimeout(() => {
                            $scope.$apply(() =>{
                                _.each(chunks.splice(0, 1), x => {
                                    tenant['applicationsView'].push(...x)
                                })
                            });
                            loop();
                        }, 1);
                    }
                };
                loop();
            };

            _.map(res.data.data, x => {
                x['projectCount'] = _.size(x['applications']);
                const getCount = (filter = _.identity) => _.reduce(x['applications'], (memo, y) => {
                    y['contracts'] = _.sortBy(y['contracts'], [z => {
                        z.className = '';
                        const getClassName = (condition, className) => {
                            return condition ? className : ''
                        };
                        z.className += getClassName(+z.Status === 2 || +z.isOverdue === 1, 'red');
                        z.className += getClassName(+z.Status === 1 && +z.isOverdue !== 1, 'green');
                        z.className += getClassName(+z.Status === 3 && +z.isOverdue !== 1, 'gray');
                        z.statusTpl = +z.isOverdue === 1 ? ('禁用时间:' + z.overdueTime + '<br/>禁用原因:' + z.overdueReason) : '';
                        z.statusText = +z.isOverdue === 1
                            ? '已禁用'
                            : (+z.Status === 1 ? '正常' : +z.Status === 2 ? '即将过期' : '已过期');
                        return _.findIndex($scope.apps, k => k.name === z.appName);
                    }]);
                    return memo + _.size(filter(y['contracts']));
                }, 0);

                x['payAuthCount'] = getCount(xs => _.reject(xs, x => _.some(['5001', '5009', '5008', '5021'], y => y === x.appCode)));
                x['freeAuthCount'] = getCount(xs => _.filter(xs, x => _.some(['5001', '5009', '5008', '5021'], y => y === x.appCode)));

                _.map(x['applications'], y => {
                    y['productNames'] = _.map(y['contracts'], 'appName').join('，');
                    y['isSetRemind'] = _.some(y['contracts'], z => +z.isSetRemind === -1 && !(+z.Status === 1 || +z.isOverdue === 1));
                }, '');
            });
            $scope.authData = res.data.data;
            $scope.pageTotal = res.data.total;
            _.each($scope.authData, interrupt);
        });
}

function getSyncAuthProject($http, $scope) {
    ui.loading(null, '同步中...');
    let url = '/orgapi/index.php?r=mtp/myscrm-organization/sync-org-project-auth-list';
    $http.get(url, {
        params: {}
    }).then(res => {
        //do something
    });
}

function ajax(options) {
    util.myAjax({
        url: options.url,
        data: options.data,
        type: options.type || 'GET',
        success: (res) => {
            if (res.retCode == 0) {
                if (typeof options.success === 'function') {
                    options.success(res);
                }
            } else {
                util.alert('系统错误');
            }
        }
    });
}

function isCountkey(keyCode) {
    return keyCode >= 65 && keyCode <= 90 ||
        keyCode >= 96 && keyCode <= 105 ||
        keyCode >= 48 && keyCode <= 57;
}

(($) => {
    $.fn.autoComplete = function (options) {
        return this.each(function () {
            let $this = $(this);
            if (!$this.data('autoComplete')) {
                $this.data('autoComplete', true);
                let timer = null;
                let $list = $('<div class="temp-autocomplete"></div>');
                $this.after($list);
                $this.on({
                    keyup: function (ev) {
                        ev.stopPropagation();
                        clearTimeout(timer);
                        timer = setTimeout(() => {
                            let key = ev.keyCode;
                            let val = $this.val().trim();
                            if (val && (key == 8 || key == 46 || key == 32) &&
                                key != 38 && key != 40 ||
                                isCountkey(key)) {
                                ajax({
                                    url: options.url,
                                    data: {
                                        keyword: val,
                                        limit: 10000
                                    },
                                    success: (res) => {
                                        let listDOM = [];
                                        res.data.forEach((v) => {
                                            listDOM.push(
                                                `<p data-phone="${v.MobilePhone}" data-email="${v.Email}" data-iid="${options.id}" data-guid="${v.UserGUID}">${v.UserName}</p>`
                                            );
                                        });
                                        $list.html(listDOM.join(''));
                                    }
                                });
                            }
                        }, 200);
                    }
                });
                $list.on('click', 'p', function () {
                    let $p = $(this);
                    $this.val($p.text());
                    $list.empty();
                    options.select({
                        type: $this.attr('data-type'),
                        name: $p.text(),
                        email: $p.attr('data-email'),
                        phone: $p.attr('data-phone'),
                        guid: $p.attr('data-guid'),
                        id: $p.attr('data-iid')
                    });
                });
            }
        });
    };
})($);
